package com.qujia.station.service.impl;

import com.qujia.common.exception.BaseException;
import com.qujia.common.utils.DateUtils;
import com.qujia.station.domain.WarehouseBatch;
import com.qujia.station.mapper.WarehouseBatchMapper;
import com.qujia.station.service.WarehouseBatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("warehouseBatchService")
@Slf4j
public class WarehouseBatchServiceImpl implements WarehouseBatchService {

    @Autowired
    private WarehouseBatchMapper warehouseBatchMapper;

    @Override
    public WarehouseBatch addWarehouseBatch(WarehouseBatch warehouseBatch) {
        WarehouseBatch batch = new WarehouseBatch();
        synchronized (this) {
            String batchNo = getBatchNo(warehouseBatch);
            warehouseBatch.setBatchNo(batchNo);
            warehouseBatchMapper.insertSelective(warehouseBatch);
            // 返回id
            batch = warehouseBatchMapper.selectWarehouseBatch(warehouseBatch);
        }
        return batch;
    }

    // 生成批次号 20240200001
    private String getBatchNo(WarehouseBatch warehouseBatch){
        String batchNo = "";
        String time = DateUtils.parseDateToStr(DateUtils.YYYYMM,new Date());
        WarehouseBatch lastWarehouseBatch = warehouseBatchMapper.selectLastWarehouseBatch(warehouseBatch);
        if(Objects.isNull(lastWarehouseBatch)){
            batchNo = time + "00001";
            return batchNo;
        }
        String lastBatchNo = lastWarehouseBatch.getBatchNo();
        if(time.equals(lastBatchNo.substring(0,6))){
            int num =Integer.valueOf(lastBatchNo.substring(7));
            num  = num + 1;
            if(num >= 100000){
                throw new BaseException("本月批次号已经封顶，请下月再创建");
            }
            String format = String.format("%05d", num);
            return time + format;
        }
        return time + "01";
    }

    @Override
    public List<WarehouseBatch> selectWarehouseBatchList(WarehouseBatch warehouseBatch) {
        return warehouseBatchMapper.selectWarehouseBatchList(warehouseBatch);
    }

    @Override
    public WarehouseBatch selectWarehouseBatch(Long id) {
        return warehouseBatchMapper.selectWarehouseBatchById(id);
    }

    @Override
    public int updateWarehouseBatch(WarehouseBatch warehouseBatch) {
        return warehouseBatchMapper.updateByPrimaryKeySelective(warehouseBatch);
    }
}
